package main

import (
	"fmt"
	"net/http"
	"html/template"
	"time"
	"github.com/gin-gonic/gin"
)
func UnixToTime(timestamp int)string{
	fmt.Println(timestamp)
	t:=time.Unix(int64(timestamp),0)
	return t.Format("2006-01-02 15:04:05")
}
func Println(str1 ,str2 string)string{
	fmt.Println(str1+str2)
	return str1+str2
}
type User struct{
	Username string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
}
func main(){
	r:=gin.Default()
	//自定义模板函数
	r.SetFuncMap(template.FuncMap{
		"UnixToTime":UnixToTime,
		"Println":Println,
	})
	//第一个参数表示路由 第二个参数表示映射的文件目录
	r.Static("/static","./static")
	r.LoadHTMLGlob("templates/**/*")
	r.GET("/index",func(c *gin.Context){
		c.HTML(http.StatusOK,"demin/index.html",map[string]interface{}{
			"title":"this is a title",
			"date":1749285662,
			"msg1":"hello ",
			"msg2":"world",
		})
		//获取get传值
		username:=c.Query("username")
		age:=c.Query("age")
		id:=c.DefaultQuery("page","1")
		c.JSON(http.StatusOK,gin.H{
			"username":username,
			"age":age,
			"id":id,
		})
	})
	//获取前端传过来的数据 get传值绑定结构体上
	r.GET("/user",func(c *gin.Context){
		c.HTML(http.StatusOK,"demin/user.html",map[string]interface{}{})
	})
	r.POST("/doAddUser",func(c *gin.Context){
		username:=c.PostForm("username")
		password:=c.PostForm("password")
		c.JSON(http.StatusOK,gin.H{
			"username":username,
			"password":password,
		})
	})
	r.POST("/doAddUser2",func(c* gin.Context){
		user:=&User{}
		err:=c.ShouldBind(user)
		if err==nil{
			c.JSON(http.StatusOK,user)
		}else{
			c.JSON(http.StatusOK,err.Error())
		}
	})
	//将get获取的参数传入结构中
	r.GET("/getUser",func(c *	gin.Context){
		user:=&User{}
		err:=c.ShouldBind(user)
		fmt.Printf("%#v",user)
		if err==nil{
			c.JSON(http.StatusOK,user)
		}else{
			c.JSON(http.StatusOK,gin.H{
				"err":err.Error(),
			})
		}
	})
	r.Run()
	fmt.Println("hello world")
}